<script setup>
import { onBeforeUnmount } from "vue";
import {
  Editor,
  Toolbar,
  getEditor,
  removeEditor,
} from "@wangeditor/editor-for-vue";

const emit = defineEmits(["htmlChange"]);
// 定义一个编辑器 id ，要求：全局唯一且不变！！！
const editorId = "bbmEditor-1";
const defaultHtml = "";
const mode = "default";
// toolbar配置
const toolbarConfig = {
  excludeKeys: [],
};
// 编辑器配置
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    /* 菜单配置 */
  },
};

// 回调函数
const handleChange = (editor) => {
  // console.log("change:", JSON.stringify(editor.children));
  // console.log("change:", editor.getHtml());
  let html = editor.getHtml();
  emit("htmlChange", html);
  // console.log(editor.getAllMenuKeys());
};

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = getEditor(editorId);
  if (editor == null) return;

  // 销毁，并移除 editor
  editor.destroy();
  removeEditor(editorId);
});
</script>

<template>
  <div style="border: 1px solid #ccc">
    <!-- 工具栏 -->
    <Toolbar
      :defaultConfig="toolbarConfig"
      :mode="mode"
      :editorId="editorId"
      style="border-bottom: 1px solid #ccc; z-index: 111"
    />
    <!-- 编辑器 -->
    <Editor
      :editorId="editorId"
      :defaultConfig="editorConfig"
      :defaultHtml="defaultHtml"
      @onChange="handleChange"
      style="height: 500px; z-index: 111"
    />
  </div>
</template>

<!-- 别忘了引入样式 -->
<style src="@wangeditor/editor/dist/css/style.css"></style>
